import hmacsha1 from 'hmacsha1'

/**
 * @description 根据key值获取query参数
 * @param key
 * @returns
 */
export function getQuery(key: string) {
  return new URLSearchParams(location.search).get(key)
}

/**
 * @description 兼容性获取媒体流
 * @param constrains
 * @returns
 */
export async function getMediaStream(constrains: MediaStreamConstraints): Promise<MediaStream> {
  return new Promise((resolve, reject) => {
    const navigatorGetUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      return navigator.mediaDevices.getUserMedia(constrains).then(resolve)
    } else if (navigatorGetUserMedia) {
      return navigatorGetUserMedia(constrains, resolve, reject)
    } else if (
      navigator.userAgent.toLowerCase().match(/chrome/) &&
      location.origin.indexOf('https://') < 0
    ) {
      reject(
        new Error(
          'chrome下获取浏览器媒体功能，因为安全性问题，需要在localhost或127.0.0.1或https下才能获取权限'
        )
      )
    } else {
      reject(new Error('无法获取浏览器媒体功能，请升级浏览器或使用chrome'))
    }
  })
}

export const errorMap = {
  NotAllowedError: '媒体设备已被禁用，请在当前浏览器设置中开启后重试',
  AbortError: '硬件问题，导致无法访问媒体设备',
  NotFoundError: '未检测到可用媒体设备',
  NotReadableError: '操作系统上某个硬件、浏览器或者网页层面发生错误，导致无法访问媒体设备',
  OverConstrainedError: '未检测到可用媒体设备',
  SecurityError: '媒体设备已被禁用，请在系统设置或者浏览器设置中开启后重试',
  TypeError: '类型错误，未检测到可用媒体设备'
}

/**
 * @description 产生uuid 跟URL.createObjectURL相同
 * @returns
 */
export function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

export function getSignature(key: string, data: string): string {
  return hmacsha1(key, data)
}

export function blobToArraybuffer(blob: Blob) {
  return new Promise<ArrayBuffer>((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => {
      if (reader.result) {
        resolve(reader.result as ArrayBuffer)
      } else {
        reject(null)
      }
    }
    reader.readAsArrayBuffer(blob)
  })
}